package com.wanggsx.library.base.views.pagerscrollerNew;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

/**
 * Created by wanggsx on 15/12/9.
 */
public class HorizontalPagerScroller extends HorizontalScrollView {

    private Context mContext;
    public LinearLayout mContainer;
    private ScrollListener mListener;

    private int MOVE_SMALL_DISTANCE = 80;

    public HorizontalPagerScroller(Context context) {
        super(context);
    }

    public HorizontalPagerScroller(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        setHorizontalScrollBarEnabled(false);
    }

    /**
     * 初始化容器的尺寸及位置
     *
     * @param width        宽度
     * @param height       高度
     * @param marginLeft   左边距
     * @param marginTop    上边距
     * @param marginRight  右边距
     * @param marginBottom 底边距
     */
    public void initScrollerLocation(int width, int height, int marginLeft, int marginTop, int marginRight, int marginBottom, ScrollListener l) {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, height);
        params.setMargins(marginLeft, marginTop, marginRight, marginBottom);
        setLayoutParams(params);
        mListener = l;
    }

    /**
     * 设置监听事件，用于绑定数据
     *
     * @param l
     */
    public void setListener(ScrollListener l) {
        mListener = l;
    }


    /**
     * 设置页数
     *
     * @param num         总页数
     * @param layoutId    布局文件id
     * @param width       页宽
     * @param height      页高
     * @param marginLeft  页的左外边距(最后一个页的右外边距同左，其余右边距为0)
     * @param paddingLeft 容器的左内边距(右内边距同左)
     */
    public void initPagerLocation(int num, int layoutId, int width, int height, int marginLeft, int paddingLeft) {
        Log.d("wan", "wanggsx 初始化pager");
        removeAllViews();
        mContainer = new LinearLayout(mContext);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mContainer.setLayoutParams(params);
        addView(mContainer);
        mContainer.setPadding(paddingLeft, 0, paddingLeft, 0);
        totalPage = num;
        currentPageIndex = 0;
        originX = 0;
        scrollerPaddingLeftOrRight = paddingLeft;
        pagerLayoutId = layoutId;
        pagerWidth = width;
        pagerHeight = height;
        pagerMarginLeft = marginLeft;
        //从一个pager到另一个pager的实际距离
        pagerTotalWith = width + marginLeft;
        currentPageIndex = 0;
        if (totalPage >= 3) {
            for (int i = 0; i <= 2; i++) {
                View child = getViewFromLayout(null, i);
                mContainer.addView(child);
            }
        } else if (totalPage == 2) {
            View child = getViewFromLayout(null, 0);
            mContainer.addView(child);
            View child1 = getViewFromLayout(null, 1);
            mContainer.addView(child1);
        } else if (totalPage == 1) {
            View child = getViewFromLayout(null, 0);
            mContainer.addView(child);
        }
    }

    private int pagerLayoutId, pagerWidth, pagerHeight;

    private View getViewFromLayout(View view, int position) {
        Log.d("wan", "wanggsx getViewFromLayout position:" + position);
        View child = view;
        if (view == null) {
            child = LayoutInflater.from(mContext).inflate(pagerLayoutId, null);
        }
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(pagerWidth, pagerHeight);
        params.setMargins(pagerMarginLeft, 0, (totalPage == position + 1) ? pagerMarginLeft : 0, 0);
        child.setLayoutParams(params);
        child.setTag(position);
        mListener.setViewData(position, child);
        if (totalPage == position + 1) {
            tfIsSetFinish = true;
        }
        return child;
    }

    public void setPageSize(int pageSize) {
        totalPage = pageSize;
    }

    private int totalPage, currentPageIndex, pagerTotalWith, scrollerPaddingLeftOrRight, pagerMarginLeft;
    private float startMoveX, scrollDistance, originX;
    private boolean tfIsFirstMove = true;
    private boolean tfIsSetFinish = false;

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        getParent().requestDisallowInterceptTouchEvent(true);
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (mContainer == null) return false;
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startMoveX = ev.getX();
                tfIsFirstMove = false;
                break;
            case MotionEvent.ACTION_UP:
                boolean isNeedDelt = false;
                scrollDistance = ev.getX() - startMoveX;
                if (scrollDistance > 0) {
                    //向右滑
                    if (scrollDistance > MOVE_SMALL_DISTANCE) {
                        if (currentPageIndex >= 1) {
                            mListener.onScrollToFront(--currentPageIndex);
                        }
                    }
                } else {
                    //向左滑
                    if (scrollDistance < -MOVE_SMALL_DISTANCE) {
                        if (currentPageIndex <= totalPage - 2) {
                            mListener.onScrollToNext(++currentPageIndex);
                            if (currentPageIndex <= totalPage - 2 && (int) mContainer.getChildAt(mContainer.getChildCount() - 1).getTag() <= currentPageIndex) {
                                if (tfIsSetFinish) {
                                    View v = mContainer.getChildAt(mContainer.getChildCount() - 1);
                                    getViewFromLayout(v, (int) v.getTag());
                                    tfIsSetFinish = false;
                                }
                                mContainer.addView(getViewFromLayout(null, currentPageIndex + 1));
                                isNeedDelt = true;
                            }
                        }
                    }
                }
                originX = pagerTotalWith * currentPageIndex;
                smoothScrollTo((int) (originX), 0);
                if (isNeedDelt) {
                    postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            smoothScrollBy(pagerMarginLeft * 11 / 10, 0);
                        }
                    }, 150);
                }
                tfIsFirstMove = true;
                break;
            case MotionEvent.ACTION_MOVE:
                if (tfIsFirstMove) {
                    startMoveX = ev.getX();
                    tfIsFirstMove = false;
                }
                originX = pagerTotalWith * currentPageIndex;
                float scrollDistance = ev.getX() - startMoveX;
                scrollTo((int) (originX - scrollDistance), 0);
                break;
            case MotionEvent.ACTION_CANCEL:
                originX = pagerTotalWith * currentPageIndex;
                smoothScrollTo((int) originX, 0);
                tfIsFirstMove = true;
                break;
        }
        return true;
    }

    public void scrollToPageIndex(int position) {
        currentPageIndex = position;
        if (position >= 2) {
            for (int i = 2; i <= (position + 1 == totalPage ? position : position + 1); i++) {
                checkAndViewIfNeed(i);
            }
        }
        originX = pagerTotalWith * currentPageIndex;
        postDelayed(new Runnable() {
            @Override
            public void run() {
                smoothScrollTo((int) originX, 0);
            }
        }, 200);
    }

    void checkAndViewIfNeed(int position) {
        if (mContainer.getChildCount() - 1 < position) {
            mContainer.addView(getViewFromLayout(null, position));
        } else if ((int) mContainer.getChildAt(position).getTag() != position) {
            mContainer.addView(getViewFromLayout(null, position), position);
        }
    }

}
